﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ext.Net;
using System.Globalization;
using BitPortal.Models;
using BitPortal.Business;
using BitPortal.Utils;
using System.Web.Services;

namespace BitPortal.Handlers
{
    /// <summary>
    /// Trả về danh sách Culture bắt đầu bằng chữ cái nhập vào
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class LanguageListRequest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            var start = 0;
            var limit = 10;
            string sort = null;
            string dir = null;
            string query = "";
            if (!string.IsNullOrEmpty(context.Request["query"]))
            {
                query = context.Request["query"];
            }
            if (!string.IsNullOrEmpty(context.Request["start"]))
            {
                start = context.Request["start"].ToInt32TryParse();
            }
            if (!string.IsNullOrEmpty(context.Request["limit"]))
            {
                limit = context.Request["limit"].ToInt32TryParse();
            }
            if (!string.IsNullOrEmpty(context.Request["sort"]))
            {
                sort = context.Request["sort"];
            }
            if (!string.IsNullOrEmpty(context.Request["dir"]))
            {
                query = context.Request["dir"];
            }
            var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures).ToList().Where(ent => ent.DisplayName.StartsWith(query, StringComparison.OrdinalIgnoreCase)).Select(ent => new { DisplayName = ent.DisplayName, Name = ent.Name }).ToList();
            int count = cultures.Count;
            cultures = cultures.DataProcessing(null, sort: sort, dir: dir, start: start, limit: limit);
            context.Response.Write(string.Format("{{total:{1},'cultures':{0}}}", JSON.Serialize(cultures), count));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}